<?php

class MemberAction extends CommonAction
{

    public function _initialize()
    {
        parent::_initialize();
        $this->checkUserAttr();
        //获取用户基本信息
        $user = $this->getLoginUserInfo();
        $credits = $this->getHotCredit();
        $dis = $this->getHotMallDis();
        $this->assign('credits', $credits);
        $this->assign('dis', $dis);
        $this->assign('user', $user);
        $this->assign('nav', 100);
    }

    public function index()
    {

    }

    /**
     * 用户中心首页显示
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function home()
    {
        $this->seoSet('个人中心');
        $this->assign('m_nav', 1);
        $this->display();
    }

    /**
     * 用户基本信息设置
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function setting()
    {
        $this->seoSet('资料设置');
        //获取用户基本信息
        $user = $this->getLoginUserInfo('id,name,email,sex,birthday,phone,status');
        //获取手机绑定情况
        if ($user['status'] == 2 && !empty($user['phone'])) {
            //手机绑定替换手机号码
            if (strlen($user['phone']) == 11) {
                $user['phone'] = substr($user['phone'], 0, 3) . "*****" . substr($user['phone'], 8, 3);
            } else {
                $user['phone'] = '*****************';
            }
            $user['isPhone'] = true;
        }
        //第三方帐号绑定情况
        //判断用户有没有绑定
        $OAuthModel = D('OAuth');
        $binds = $OAuthModel->getUserBind($user['id']);
        foreach ($binds as $key => $bind) {
            $binds[$bind['site']] = $bind;
            unset($binds[$key]);
        }
        $this->assign('binds', $binds);
        $this->assign('user', $user);
        $this->display();
    }

    /**
     * 积分兑换管理
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function credit()
    {
        if ($this->isAjax()) {
            $status = 0;
            $id = intval(getGet('id'));
            $uid = intval(getGet('uid'));
            if ($id && $uid) {
                $map = array();
                $map['lid'] = $id;
                $map['uid'] = $uid;
                $limited = M('LimitedUsers')->where($map)->find();
                if ($limited && $limited['send_count'] < 5) {
                    $verify = $limited['verify']; //获取验证码
                    $phone = $limited['phone']; //获取手机号码
                    $ulid = $limited['id'];
                    //获取优惠信息
                    $limited = M('Limited')->find($id);
                    //获取领取地址
                    $fMall = D('Market')->getById($limited['mid']);
                    $address = $fMall['m_name'];
                    if ($limited['fid']) {
                        $fFloor = D('Floor')->getById($limited['fid']);
                        $address .= $fFloor['f_sain'];
                    }
                    //发送短信通知
                    $smsBody = $limited['title'] . '领取手机认证码：' . $verify . '领取地点：' . $address . C('SMS_FOOT');
                    $smsUser = array();
                    $smsUser[$uid] = $phone;
                    $rs = smsSend($smsUser, $smsBody); //执行发送
                    if ($rs) {
                        $data = '短信发送成功，注意查收！';
                        $status = 1;
                        //更新当前发送数量
                        M('LimitedUsers')->setInc('send_count', 'id = ' . $ulid, 1);
                    } else {
                        $data = '短信发送失败，等等在试！';
                    }
                } else if ($limited['send_count'] >= 5) {
                    $data = '当前短信发送数量已到达上限！如还没有收到短信，请联系管理！';
                } else {
                    $data = '提供的数据不对！';
                }
            } else {
                $data = '提供的数据不对！';
            }
            $this->ajaxReturn($data, null, $status);
            exit;
        }
        $uid = getLoginUserInfo();
        $LimitedModel = D('Limited');
        $allCount = $LimitedModel->getUserJoinCount($uid);
        if ($allCount > 1) {
            $Page = $this->getPage($allCount, 5);
            $limiteds = $LimitedModel->getUserJoin($uid, $Page->firstRow . ',' . $Page->listRows);
            foreach ($limiteds as $key => $limited) {
                if ($limited) {
                    $LimitedModel->getAddress($limiteds[$key]);
                    $limiteds[$key]['image_url'] = $LimitedModel->getManagedUrl($limited['image'], 'limited');
                    //进行时间判断 进行中 进行中和领取中 领取中 结束
                    $statis_dis = '';
                    //时间对比
                    $time = time();
                    //获取是否在发放状态中
                    $s1 = $limiteds[$key]['start_time'] < $time && $time < $limiteds[$key]['end_time'];
                    //获取是否在领取状态中
                    $s2 = $limiteds[$key]['receive_start_time'] < $time && $time < $limiteds[$key]['receive_end_time'];
                    if ($s1) {
                        $statis_dis = '进行中';
                    } else if ($s1 && $s2) {
                        $statis_dis = '进行和领取中';
                    } else if ($s2) {
                        $statis_dis = '领取中';
                    } else {
                        $statis_dis = '结束';
                    }
                    $statis_dis .= ' 你已经领取验证码';
                    $limiteds[$key]['status_dis'] = $statis_dis;
                    $push = 0;
                    if ($limited['model'] == 2) {
                        $push = $LimitedModel->getMallPush($limited['lid']);
                        $join = $LimitedModel->getPush($limited['lid']);
                    } else {
                        $push = $LimitedModel->getPush($limited['lid']);
                    }
                    $limiteds[$key]['push'] = $limited['count'] - $push;
                }
            }
            $this->assign('page', $Page->show());
            $this->assign('limiteds', $limiteds);
        }
        $this->assign('m_nav', 3);
        $this->display();
    }

    /**
     * 用户基本资料信息修改
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function update()
    {
        $user = $this->getLoginUserInfo();
        if ($this->isPost() && $user) {
            $data = array();
            $data['id'] = getLoginUserInfo();
            $name = hh(trim($this->_post('name')));
            $sex = intval($this->_post('sex'));
            if ($sex != 1 && $sex != 2) {
                $this->errorLang('_SEX_SELECTION_ERROR_');
            }
            $data['sex'] = $sex;
            $data['name'] = $name;
            $year = intval($this->_post('year'));
            $month = intval($this->_post('month'));
            $day = intval($this->_post('day'));
            if (!$data['name']) {
                $this->errorLang('_NAME_MUST_');
            }
            if ($year && $month && $day) {
                $birthday = $year . '-' . $month . '-' . $day;
                $data['birthday'] = strtotime($birthday);
            } else {
                $this->errorLang('_BIRTHDAY_MUST_');
            }
            if ($data['birthday'] > time()) {
                $this->errorLang('_BIRTHDAY_TIME_ERROR_');
            } else if ($data['birthday'] < time() - (60 * 60 * 24 * 365 * 120)) {
                $this->errorLang('_AGE_ERROR_');
            }
            //昵称重复判断
            $UsersModel = D('Users');
            if($user['name'] != $data['name']){
                if ($UsersModel->getCountByName($data['name'])) {
                    $this->error('此昵称已经被人使用！');
                    exit;
                }
            }
            $rs = $UsersModel->save($data);
            if ($rs) {
                $this->successLang('_USER_DATA_EDIT_SUCCESS_');
            } else {
                $this->errorLang('_USER_DATA_EDIT_ERROR_');
            }
        }
    }

    /**
     * 用户密码修改
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function passwd()
    {
        $user = $this->getLoginUserInfo('id,pwd');
        if ($this->isPost() && $user) {
            $nowpwd = md5($this->_post('nowpwd'));
            $pwd = trim($this->_post('pwd'));
            $repwd = trim($this->_post('repwd'));
            if ($nowpwd != $user['pwd']) {
                $this->errorLang('_CURRENT_PASSWORD_ERROR_');
            }
            if ($pwd && $repwd) {
                if ($pwd == $repwd) {
                    $UsersModel = M('Users');
                    //执行密码修改
                    $data = array();
                    $data['id'] = $user['id'];
                    $data['pwd'] = md5($pwd);
                    $rs = $UsersModel->save($data);
                    if ($rs) {
                        $this->successLang('_PASSWORD_SUCCESSFULLY_CHANGED_');
                    } else {
                        $this->errorLang('_PASSWORD_CHANGED_FAILED_');
                    }
                } else {
                    $this->errorLang('_TWO_PASSWORD_DIFFERENT_');
                }
            } else {
                $this->errorLang('_TWO_PASSWORD_MUST_');
            }
        }
    }

    /**
     * 用户手机认证
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function phone()
    {
        //变量声明区
        $user = $this->getLoginUserInfo();
        $uid = $user['id'];
        $UsersModel = D('Users');
        //判断用户是否已经通过验证
        $rs = $UsersModel->checkUsePhone($uid);
        if ($rs['status']) {
            $this->assign('jumpUrl', U('/member/home'));
            $this->error($rs['data']);
        }
        //进行提交验证
        if ($this->isPost()) {
            $phone = $this->_post('phone');
            $verify = strtoupper($this->_post('verify'));
            if ($phone && $verify) {
                $UserPhoneModel = D('UserPhone');
                $phoneUser = $UsersModel->checkPhoneIsUse($phone);
                if ($phoneUser) {
                    $this->error('手机号码已经被其他用户绑定！');
                }
                //执行手机号码性验证
                $phoneVerify = $UserPhoneModel->getUidPhoneVerify($uid, $phone, 1, false);
                if ($phoneVerify) {
                    //进行手机验证码对比
                    if ($phoneVerify['verify'] != $verify) {
                        $this->error('验证码输入不对！');
                    }
                    //调整短信认证状态
                    $rs = $UserPhoneModel->updateUidPhoneVerify($uid, $phone, $phoneVerify['verify'], 2);
                    if (!$rs) {
                        $body['body'] = '手机认证状态修改失败！ ';
                        $this->sendErrorMail(null, $body, __CLASS__, __LINE__);
                        $this->error('手机认证状态修改失败！');
                    }
                    $rs = $UsersModel->updateUserStatus($uid, 2, $phone);
                    if (!$rs) {
                        $body['body'] = '用户手机认证状态修改失败！ ';
                        $this->sendErrorMail(null, $body, __CLASS__, __LINE__);
                        $this->error('用户状态修改失败！');
                    }
                    //判断用户是否是邀请用户和给邀请者添加积分 -- 用户绑定第一次为添加邀请用户分如果 判断用户手机号码是否存在
                    //存在就不是第一次绑定，不存在就是第一次绑定
                    //判断当前用户是否是被邀请用户
                    $inviteUser = M('InviteUser')->where('invite_uid=' . $uid)->find();
                    if ($inviteUser) {
                        D('CreditUser')->change($inviteUser['uid'], 2); //执行邀请人积分添加
                    }
                    //给当前用户添加绑定积分只有一次机会
                    D('CreditUser')->change($uid, 3); //执行登陆积分操作
                    //修改用户状态
                    $this->assign('jumpUrl', U('/member/setting', null, false, false));
                    $this->success('用户认证成功！');
                } else {
                    //TODO 详细分析错误原因
                    $this->error('用户认证失败！因为你的验证信息不对！');
                }
            } else {
                $this->error('请填写完整信息,手机和验证码必须填写！');
            }
        }
    }

    /**
     * 用户邀请连接生成
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function invite()
    {
        $user = $this->getLoginUserInfo();
        $uid = getLoginUserInfo();
        //获取邀请好友数量
        $InviteUserModel = D('InviteUser');
        $inviteCount = $InviteUserModel->getInviteUserCount($uid); //邀请总数获取
        $inviteUsePhoneCount = $InviteUserModel->getInviteUserPhoneCount($uid); //获取通过认证的好友说了
        $inviteUrl = $uid . C('URL_PATHINFO_DEPR') . $user['name'];
        //默认获取10个好友
        $Page = new Page($inviteCount, 10);
        $users = $InviteUserModel->getUsers($uid, $Page->firstRow . ',' . $Page->listRows);
        $this->assign('users', $users);
        $this->assign('page', $Page->show());
        $this->assign('inviteUrl', $inviteUrl);
        $this->assign('invite_count', $inviteCount);
        $this->assign('invite_phone', $inviteUsePhoneCount);
        $this->assign('invite_no_phone', $inviteCount - $inviteUsePhoneCount);
        $this->seoSet('邀请好友');
        $this->assign('m_nav', 4);
        $this->display();
    }

    /**
     * 用户关注
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function attentionMall()
    {
        $this->seoSet('商场关注');
        $uid = getLoginUserInfo();
        $malls = D('MarketAttention')->getAttr($uid);
        $this->assign('malls', $malls);
        $this->assign('m_nav', 2);
        $this->display();
    }

    /**
     * 用户关注
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function attentionBrand()
    {
        $this->seoSet('品牌关注');
        //获取品牌首字母
        $uid = getLoginUserInfo();
        $initials = D('BrandAttention')->getInitials($uid);
        $this->assign('initials', $initials);
        $this->assign('m_nav', 2);
        $this->display();
    }

    /**
     * 用户积分显示
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function score()
    {
        $this->seoSet('我的积分');
        $uid = getLoginUserInfo();
        $CreditLogModel = D('CreditLog');
        $CreditUserModel = D('CreditUser');
        $logs = $CreditLogModel->getUserLogs($uid, 1);
        $userScore = $CreditUserModel->getUserNum($uid, 1);
        $this->assign('logs', $logs);
        $this->assign('score', $userScore);
        $this->assign('m_nav', 5);
        $this->display();
    }

    /**
     * 第三方审核平台
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function oauth()
    {
        //判断用户有没有绑定
        $OAuthModel = D('OAuth');
        $uid = getLoginUserInfo();
        $binds = $OAuthModel->getUserBind($uid);
        foreach ($binds as $key => $bind) {
            $binds[$bind['site']] = $bind;
            unset($binds[$key]);
        }
        $this->assign('binds', $binds);
        $this->display();
    }

    /**
     * 获取当前用户关注品牌资讯
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function getAttBrandDis()
    {
        //获取关注品牌有资讯
        $uid = getLoginUserInfo();
        $news = D('BrandAttention')->getBrandsNew($uid);
        //获取关注品牌有特卖
        $dis = D('MallDiscount')->getBrandsDis($uid);
        //合并信息
        foreach ($dis as $key => $d) {
            if (empty($news[$key])) {
                $news[$key]['brand'] = $d['brand'];
            }
            $news[$key]['dis'][] = $d;
        }
        $this->assign('news', $news);
        $this->ajaxReturn($this->fetch(), 0, 1);
    }

    /**
     * 获取当前用户关注商场资讯
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function getAttMallDis()
    {
        //获取关注商场有资讯
        $uid = getLoginUserInfo();
        $dis = D('MarketAttention')->getAttDis($uid);
        $this->assign('dis', $dis);
        $this->ajaxReturn($this->fetch(), 0, 1);
    }

    /**
     * 获取关注品牌数据
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function getAttentionBrand()
    {
        $uid = getLoginUserInfo();
        $i = $this->_get('i');
        $brands = D('BrandAttention')->getInitialsBrands($uid, $i);
        $this->assign('brands', $brands);
        //$this->display();
        $this->ajaxReturn($this->fetch(), 0, 1);
    }

    /**
     * 发送用户手机验证码
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function sendUserPhoneVerify()
    {
        //Vendor('sms.sms');
        if (!$this->isAjax()) {
            exit;
        }
        $data = '短信发送条件不满足！';
        $status = 0;
        //进行手机号码格式验证
        $phone = trim($this->_get('phone'));
        $type = intval($this->_get('type'));
        $id = intval($this->_get('id'));
        $type = $type ? $type : 1; //默认是用户认证短信发送
        $rs = $this->regex($phone, 'integer'); //简约验证短信发送端口会进行再次验证
        $rss = intval(msubstr($rs, 0, 1)) === 1;
        if ($rs && $rss) {
            //获取用户信息
            $user = $this->getLoginUserInfo();
            $uid = $user['id'];
            $UserPhoneModel = D('UserPhone');
            //检查手机号码一天发送量
            $phoneSendCount = $UserPhoneModel->checkDaySendCount($phone);
            $userSendCount = $UserPhoneModel->checkDaySendCount($phone, $uid, 2);
            if ($phoneSendCount > 5) {
                $this->ajaxReturn('当前手机一天只能发送5条短信！', '', $status);
            }
            if ($userSendCount > 5) {
                $this->ajaxReturn('当前用户一天只能发送5条短信！', '', $status);
            }
            //验证最短发送时间间隔
            $phoneVerify = $UserPhoneModel->getUidPhoneVerify($uid, $phone, 1, true, $type, $id);
            if ($phoneVerify) {
                $data = '验证码已经发送到' . $phoneVerify['phone'] . '过啦！请15秒再试！';
            } else {
                $verify = String::randString(6, 2, '0123456789');
                //执行短信发送
                if ($type == 1) {
                    //添加判断手机认证是否重复
                    $phoneUser = D('Users')->checkPhoneIsUse($phone);
                    if ($phoneUser) {
                        $this->ajaxReturn('手机号码已经被其他用户绑定！', '', $status);
                    }
                    $smsBody = '用户手机认证码：' . $verify . C('SMS_FOOT');
                } else if ($type == 2) {
                    $limited = M('Limited')->find($id);
                    if ($limited) {
                        //获取领取地址
                        $fMall = D('Market')->getById($limited['mid']);
                        $address = $fMall['m_name'];
                        if ($limited['fid']) {
                            $fFloor = D('Floor')->getById($limited['fid']);
                            $address .= $fFloor['f_sain'];
                        }
                        $smsBody = $limited['title'] . '领取手机认证码：' . $verify . '领取地点：' . $address . C('SMS_FOOT');
                    } else {
                        $this->ajaxReturn('优惠信息有错误！', '', $status);
                    }
                }
                $smsUser = array();
                $smsUser[$uid] = $phone;
                $rs = smsSend($smsUser, $smsBody);
                //记录用户短信发送消息
                if ($rs) {
                    $UserPhoneModel->addUidPhoneVerify($uid, $phone, $verify, $type, $id);
                }
                if ($rs) {
                    $status = 1;
                    $data = '短信发送成功！请注意查收！';
                } else {
                    $status = 0;
                    $data = '短信发送失败！';
                }
            }
        } else {
            $data = '手机号码不对！';
        }
        $this->ajaxReturn($data, '', $status);
    }

}

?>